package cn.fl.finance.service.impl;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.finance.api.IFinPayApplyInfoApiService;
import cn.fl.finance.api.IFinPayDtlApiService;
import cn.fl.finance.condition.FinPayApplyInfoQC;
import cn.fl.finance.condition.FinPayDtlQC;
import cn.fl.finance.constant.FinFlowDynamicTableConstant;
import cn.fl.finance.constant.FinFlowFormUrlConstant;
import cn.fl.finance.constant.FinFlowModelConstant;
import cn.fl.finance.constant.FinPayApplyInfoConstant;
import cn.fl.finance.dto.FinPayApplyInfoDTO;
import cn.fl.finance.dto.FinPayDtlDTO;
import cn.fl.finance.service.IFinPayApplyInfoService;
import cn.fl.finance.transform.FinPayApplyInfoVOTransform;
import cn.fl.finance.util.FlowStartParmsVO;
import cn.fl.finance.vo.FinPayApplyInfoVO;
import cn.fl.framework.base.context.CurrentThreadContext;
import com.alibaba.fastjson.JSON;
import fl.flow.facade.flow.api.IFlowQueryApiService;
import fl.flow.facade.flow.condition.SysFlowSHQueryCondition;
import fl.flow.facade.flow.constant.FlowConstant;
import fl.flow.facade.flow.dto.FlowStartParamsDTO;
import fl.flow.facade.flow.dto.FlowStartedDTO;
import fl.flow.facade.flow.dto.SysFlowSHDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Description: 付款申请信息表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class FinPayApplyInfoServiceImpl implements IFinPayApplyInfoService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IFinPayApplyInfoService.class);
	
	@Autowired
	private IFinPayApplyInfoApiService finPayApplyInfoApiService;
	@Autowired
	private IFinPayDtlApiService finPayDtlApiService;
	/**
	 * 数据字典服务
	 */
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;
	@Autowired
	private IFlowQueryApiService flowQueryApiService;

	@Override
	public DataResultDTO addFlowStart(FlowStartParmsVO vo) throws BaseException {
		//200表示接口调用成功
		DataResultDTO result = new DataResultDTO("200");
		FlowStartParamsDTO flowStartParamsDTO = new FlowStartParamsDTO();
		try {
			flowStartParamsDTO.setAudStsCd(FlowConstant.FLOW_CHECK_STATE_IN);
			flowStartParamsDTO.setWordsInTheTable(FinFlowDynamicTableConstant.SPL_FLOW_S_H_CAP);
			flowStartParamsDTO.setProcDefKey(vo.getProcDefKey());
			flowStartParamsDTO.setProcDefId(vo.getProcDefId());
			flowStartParamsDTO.setProcNo(vo.getProcNo());
			flowStartParamsDTO.setBusinessKey(vo.getId());
			flowStartParamsDTO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			flowStartParamsDTO.setOrgCd(CurrentThreadContext.getCurrentOrgCd());
			flowStartParamsDTO.setBuOrgCd(CurrentThreadContext.getCurrentBuOrgCd());
			flowStartParamsDTO.setSysCd(CurrentThreadContext.getCurrentSysCd());
			flowStartParamsDTO.setInitiator(String.valueOf(CurrentThreadContext.getCurrentUserId()));
			flowStartParamsDTO.setInitiatorNm(CurrentThreadContext.getCurrentUserName());
			/*flowStartParamsDTO.setCrtUsrId(1l);
			flowStartParamsDTO.setOrgCd("0000");
			flowStartParamsDTO.setBuOrgCd("0000");
			flowStartParamsDTO.setSysCd("11000");
			flowStartParamsDTO.setInitiator(String.valueOf("1"));
			flowStartParamsDTO.setInitiatorNm("admin");*/
			flowStartParamsDTO.setProcPriority(FlowConstant.FLOW_PRIORITY_EMERGENCY);//优先级,可以在界面定义
			flowStartParamsDTO.setBusinessType(FinFlowDynamicTableConstant.FLOW_LOAN_TABLE);//确认用不用
			flowStartParamsDTO.setModelTyp(FinFlowModelConstant.FLOW_MODEL_LOAN);//需要和流程配置中的模块类型匹配
			flowStartParamsDTO.setSearchDesc(CurrentThreadContext.getCurrentOrgDispNm());
			BaseLogUtils.info(logger, "finPayApplyInfoApiService>addFlowStart", "发起借款流程->业务主键是"+vo.getId()+"请求参数是:"+JSON.toJSONString(flowStartParamsDTO));
			DataResultDTO dto = finPayApplyInfoApiService.addFlowStart(flowStartParamsDTO);
			BaseLogUtils.info(logger, "finPayApplyInfoApiService>addFlowStart", "发起借款流程->业务主键是"+vo.getId()+"返回结果是:"+JSON.toJSONString(dto));
			
			if(!dto.getCode().equals("200")){
				result.setCode(dto.getCode());
				result.setInfo(dto.getInfo());
			}
			if(dto.getCode().equals("200")){
				/*FlowStartedDTO flowStartedDTO = (FlowStartedDTO) dto.getData();
				result.setData(flowStartedDTO.getMqKey());*/
			}

		} catch (Exception e) {
			result.setCode("500");
			result.setInfo("操作失败");
			BaseLogUtils.info(logger, "addFlowStart", "借款流程操作失败信息是:"+JSON.toJSONString(e.getMessage()));
		}
		return result;
	}

	@Override
	public FinPayApplyInfoVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}

		FinPayApplyInfoDTO dto = finPayApplyInfoApiService.selectById(id);
		return FinPayApplyInfoVOTransform.toVO(dto);
	}

	@Override
	public Long add(FinPayApplyInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		return this.finPayApplyInfoApiService.add(FinPayApplyInfoVOTransform.toDTO(entity));
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.finPayApplyInfoApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(FinPayApplyInfoVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
        return finPayApplyInfoApiService.modify(FinPayApplyInfoVOTransform.toDTO(entity));

	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		//return this.finPayApplyInfoApiService.searchListPage(page);
		//TODO 业务逻辑
		return null;
	}

	@Override
	public List<FinPayApplyInfoDTO> selectList(FinPayApplyInfoQC qc) throws BaseException{
		if(StringUtils.isEmpty(qc.getLoanId())){
			BaseLogUtils.info(logger, "selectById", "借款记录ID不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		List<Long> payApplyIds = new ArrayList<>();//付款申请信息 id集合
		Map<Long,FinPayApplyInfoDTO> payApplyInfoMap = new HashMap<>();//付款申请信息 map

		//付款申请list start
		List<FinPayApplyInfoDTO> finPayApplyInfoDTOS = this.finPayApplyInfoApiService.searchList(qc);
		if(CollectionUtils.isNotEmpty(finPayApplyInfoDTOS)){
			for(FinPayApplyInfoDTO pa : finPayApplyInfoDTOS){
				payApplyIds.add(pa.getId());
				payApplyInfoMap.put(pa.getId(),pa);
			}
		}
		//付款申请list end

		//付款明细list start
		List<FinPayDtlDTO> finPayDtlDTOS = null;
		if(CollectionUtils.isNotEmpty(payApplyIds)){
			FinPayDtlQC payDtlQC = new FinPayDtlQC();
			payDtlQC.setPayApplyIds(payApplyIds);
			//按实际付款时间倒叙
			payDtlQC.setSortName("ACT_PAY_TM");
			payDtlQC.setSortOrder("DESC");
			finPayDtlDTOS = finPayDtlApiService.selectList(payDtlQC);
		}
		

		Map<Long,Date> payApplyIdActPayTmMap = new HashMap<>();//付款申请id与实际付款时间Map（存最后一条付款明细实际付款时间）
		Map<Long,Long> payApplyIdActPayAmtMap = new HashMap();//付款申请id与总实际付款金额Map
		if(CollectionUtils.isNotEmpty(finPayDtlDTOS)){
			for(FinPayDtlDTO d : finPayDtlDTOS){
				if(!payApplyIdActPayTmMap.containsKey(d.getPayApplyId())){
					payApplyIdActPayTmMap.put(d.getPayApplyId(),d.getActPayTm());
					continue;
				}
			}

			for(FinPayDtlDTO d : finPayDtlDTOS){
				if(CollectionUtils.isMapNotEmpty(payApplyInfoMap) && payApplyInfoMap.containsKey(d.getPayApplyId())){
					if(StringUtils.isNotEmpty(d.getActPayAmt())){
						Long actPayAmtSum = d.getActPayAmt();
						if(CollectionUtils.isMapNotEmpty(payApplyIdActPayAmtMap) && payApplyIdActPayAmtMap.containsKey(d.getPayApplyId())){
							payApplyIdActPayAmtMap.put(d.getPayApplyId(),actPayAmtSum + payApplyIdActPayAmtMap.get(d.getPayApplyId()));
						}else{
							payApplyIdActPayAmtMap.put(d.getPayApplyId(),actPayAmtSum);
						}
					}
				}
			}

		}
		//付款明细list end

		//拼接数据 start
		if(CollectionUtils.isNotEmpty(finPayApplyInfoDTOS)){
			for(FinPayApplyInfoDTO pa : finPayApplyInfoDTOS){
				if(CollectionUtils.isMapNotEmpty(payApplyIdActPayTmMap) && payApplyIdActPayTmMap.containsKey(pa.getId())){
					pa.setActPayTm(payApplyIdActPayTmMap.get(pa.getId()));
				}
				if(CollectionUtils.isMapNotEmpty(payApplyIdActPayAmtMap) && payApplyIdActPayAmtMap.containsKey(pa.getId())){
					pa.setActPayAmtSum(payApplyIdActPayAmtMap.get(pa.getId()));
				}
			}
		}
		//拼接数据 end

		//return FinPayApplyInfoVOTransform.toVO(dto);
		//设置数据字典及流程
		prepare(finPayApplyInfoDTOS);
		return finPayApplyInfoDTOS;
	}

	//加载数据字典数据及流程
	private void prepare(List<FinPayApplyInfoDTO> finPayApplyInfoDTOS) {
		List<SysFlowSHDTO> flowSHList = null;
		//根据付款明细id  作为主键 查询流程历史 start
		if(CollectionUtils.isNotEmpty(finPayApplyInfoDTOS)) {
			List<Long> dataIdList  = new ArrayList<>();
			for (FinPayApplyInfoDTO d : finPayApplyInfoDTOS) {
				dataIdList.add(d.getId());
			}
			if(dataIdList!=null) {
				SysFlowSHQueryCondition condition = new SysFlowSHQueryCondition();
				condition.setDataIdList(dataIdList);
				condition.setSysCd("11000");
				condition.setWordsInTheTable("CAP");
				BaseLogUtils.info(logger, "prepare", "查询流程历史API=>参数:"+JSON.toJSONString(condition));
				flowSHList = flowQueryApiService.searchFlowSHList(condition);
				BaseLogUtils.info(logger, "prepare", "查询流程历史API=>结果:"+JSON.toJSONString(flowSHList));
			}
		}
		//根据付款明细id  作为主键 查询流程历史 end

		//放款状态
		//this.sysDictionaryApiService.getKvList(FinPayApplyInfoConstant.PAY_STS_CD, CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd());
		Map<String, String> payStsCdMap = this.sysDictionaryApiService.searchGroupToMap(CurrentThreadContext.getCurrentSysCd(), CurrentThreadContext.getCurrentOrgCd(), FinPayApplyInfoConstant.PAY_STS_CD);
		//拼接数据 start
		if(CollectionUtils.isNotEmpty(finPayApplyInfoDTOS)){
			for(FinPayApplyInfoDTO f : finPayApplyInfoDTOS){

				if(CollectionUtils.isMapNotEmpty(payStsCdMap) && payStsCdMap.containsKey(f.getPayStsCd())){
					//f.setPayStsCd(payStsCdMap.get(f.getPayStsCd()));
					f.setPayStsCdNm(payStsCdMap.get(f.getPayStsCd()));
				}

				//流程历史填充到 付款申请信息中 strat
				if(CollectionUtils.isNotEmpty(flowSHList)) {
					for (SysFlowSHDTO sysFlowSHDTO : flowSHList) {
						if(sysFlowSHDTO.getDataId().equals(f.getId())) {
							f.setpNo(sysFlowSHDTO.getPNo());
							f.setpInstId(sysFlowSHDTO.getPInstId());
							f.setAudStsCd(sysFlowSHDTO.getAudStsCd());
							f.setDataId(sysFlowSHDTO.getDataId());
							if(sysFlowSHDTO.getPDefKey().equals(FinFlowModelConstant.FLOW_ASS_TRAILER_PRE_ID)){
								f.setFormUrl(FinFlowFormUrlConstant.ASS_TRAILER_FORM_URL);
							}else {
								f.setFormUrl(FinFlowFormUrlConstant.LOAN_FORM_URL);

							}
							//f.setFormUrl(FinFlowFormUrlConstant.LOAN_FORM_URL);
						}
					}
				}
				//流程历史填充到 付款申请信息中 end

			}
		}
		//拼接数据 end
	}

	
}
